﻿using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UCS.XNA.Utils.Animation
{
    public class TranslateAnimation
    {
        #region Attributes and Properties

        private float _speed;
        public float Speed
        {
            get { return this._speed; }
            set { this._speed = value; }
        }

        private Vector2 _destination;
        public Vector2 Destination
        {
            get { return this._destination; }
            set { this._destination = value; }
        }

        #endregion

        #region Private Members

        private ITranslateAnimatable _target;
        private bool _isFinished;

        #endregion

        #region Events

        public virtual event EventHandler<EventArgs> AnimationFinished;

        #endregion

        #region Constructors

        public TranslateAnimation(ITranslateAnimatable target, Vector2 destination, float speed)
        {
            this._target = target;
            this._destination = destination;
            this._speed = speed;
            this._isFinished = false;
        }

        #endregion

        #region Public Methods

        public void Update(GameTime gameTime)
        {
            if (this._target.Position != this._destination && !this._isFinished)
            {
                Vector2 direction = this._destination - this._target.Position;

                Vector2 normal = direction;
                normal.Normalize();
                normal *= this._speed;

                if (normal.Length() > direction.Length())
                    this._target.Position = this._destination;
                else
                    this._target.Position += normal;
            }
            else if (!this._isFinished)
            {
                this._isFinished = true;
                this.RaiseAnimationFinishedEvent();
            }
        }

        #endregion

        #region Protected Methods

        public void RaiseAnimationFinishedEvent()
        {
            if (this.AnimationFinished != null)
                this.AnimationFinished(this, new EventArgs());
        }

        #endregion
    }
}
